    export default {
        name: "productMain",
        setup(props) {
            const router = VueRouter.useRouter();
            const route = VueRouter.useRoute();
			const searchText = ref('')
			const currentPage = ref(1)
			const pageSize = ref(10)
			const total = ref(0)
			const product = ref([])
			const userInfo = ref(JSON.parse(localStorage.getItem('userInfo')) || {})
            const dialogVisible = ref(false);
            const dialogTitle = ref('');
            const productForm = ref(null);
            const option = ref({url: '',name: 'file',path: 'blog'});
			const uploadUrl = window.APP_CONFIG.baseurl + 'v1/dbupload';// 上传配置
            const formData = ref({
                Name: '',
                Description: [{type: 'text',value: '',f: false}],
                HiddenContent: '',
                Photo: '',
                Points: 0,
                Stock: 0,
                IsAvailable: true
            });
            const formRef = ref(null);
            const rules = reactive({
                Name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
                Photo: [{ required: true, message: '请上传图片'}],
                HiddenContent: [{ required: true, message: '请输入付费内容', trigger: 'blur' }],
                Points: [
                    { required: true, message: '请输入积分值', trigger: 'blur' },
                    { type: 'number', min: 0, message: '积分不能小于0', trigger: 'blur' }
                ],
                Stock: [
                    { required: true, message: '请输入库存数量', trigger: 'blur' },
                    { type: 'number', min: 0, message: '库存不能小于0', trigger: 'blur' }
                ]
            });

			// 生命周期钩子
			onMounted(() => {
				loadproduct();
			})

			// 加载商品数据
			const loadproduct = async () => {
			    const res = await getproductsadmin({
                    search: searchText.value.trim(),
                    page: Math.max(currentPage.value, 1),
                    pageSize: Math.min(Math.max(pageSize.value, 1), 100),
					is_available: true
				});
				product.value = res.items;
				total.value = res.total;
			}

			// 分页处理
			const handlePageChange = () => {
				loadproduct()
			}

			// 搜索处理
			const handleSearch = () => {
				currentPage.value = 1
				loadproduct()
			}

			// 清除搜索
			const clearSearch = () => {
				searchText.value = ''
				currentPage.value = 1
				loadproduct()
			}

			// 查看详情
			const viewproduct = (id) => {
				router.push({ name: 'productview', params: { id: id } })
			}

            // 创建商品
            const handleCreate = () => {
                formData.value = {
                    Name: '',
                    Description: [{type: 'text',value: '',f: false}],
                    HiddenContent: '',
                    Photo: '',
                    Points: 0,
                    Stock: 0,
                    IsAvailable: true
                };
                dialogTitle.value = '创建商品';
                dialogVisible.value = true;
            };
            
            // 修改商品
            const handleEdit = (row) => {
                formData.value = { ...row };
                dialogTitle.value = '编辑商品';
                dialogVisible.value = true;
            };

			
            // 表单提交处理
            const handleFormSubmit = async () => {
                await formRef.value.validate();
                const submitData = {
                    ...formData.value,
                    Points: Number(formData.value.Points),
                    Stock: Number(formData.value.Stock)
                };
                if (formData.value.ID) {
                    await updateproducts({id: formData.value.ID, ...submitData});
                    ElMessage.success('商品更新成功');
                } else {
                    // 创建时同理
                    await addproducts(submitData);
                    ElMessage.success('商品创建成功');
                }
                dialogVisible.value = false;
                loadproduct();
            };
            
            // 删除商品
            const handleDelete = _.debounce(async (row) => {
                console.log(row)
                if(!row.ID) return ElMessage.error('商品不存在');
                try {
                    await ElMessageBox.confirm('确定要删除该商品吗？', '删除确认', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    });
                    await delproducts({id: row.ID});
                    ElMessage.success('删除成功');
                    loadproduct();
                } catch (error) {
                    if (error === 'cancel') {
                        return;  // 用户点击了取消，不进行处理
                    }
                    console.error(' 删除失败:', error);
                    ElMessage.error(' 删除失败，请稍后再试');
                }
            }, 300);
            
			// 图片上传处理
			const handleUploadSuccess = (response, file) => {
				if (response.code === 0) {
					formData.Photo = response.url
					ElMessage.success('上传成功')
				} else {
					ElMessage.error(response.message)
				}
			}
			
			// 查看订单
            const viewPurchaseList = () => {
                router.push({ name: 'AdminPurchaseList' })
            }
            
            return {
                userInfo,
                searchText,
                currentPage,
                pageSize,
                product,
                total,
                handleSearch,
                loadproduct,
                clearSearch,
                viewproduct,
                dialogVisible,
                dialogTitle,
                formData,
                formRef,
                handleFormSubmit,
                handlePageChange,
                handleCreate,
                handleEdit,
                handleDelete,
                rules,
                uploadUrl,
                option,
                handleUploadSuccess,
                viewPurchaseList
            };
        },
        
        template: `
	<div class="container">
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="70%">
            <el-form :model="formData" ref="formRef" :rules="rules" label-position="top">
                <el-form-item label="商品名称" prop="Name">
                    <el-input v-model="formData.Name" placeholder="请输入商品名称" />
                </el-form-item>
                <el-row :gutter="10">
                    <el-col :span="8">
                        <el-form-item label="所需积分" prop="Points">
                            <el-input-number v-model="formData.Points" :min="0" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="库存数量" prop="Stock">
                            <el-input-number v-model="formData.Stock" :min="0" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="是否上架">
                            <el-switch v-model="formData.IsAvailable" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="付费内容" prop="HiddenContent" required>
                	<el-input v-model="formData.HiddenContent" type="textarea"/>
                </el-form-item>
                <el-form-item label="商品描述" prop="Description" required>
                	<kzhedit v-model="formData.Description" :option="option" style="width:100%;" />
                </el-form-item>
                <el-form-item label="缩略图" prop="Photo" required>
                	<imgpicker v-model="formData.Photo" :uploadurl="uploadUrl" :option="option"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleFormSubmit">确认</el-button>
            </template>
        </el-dialog>
	
        <div style="display: flex; align-items: center;">
            <el-button type="primary" @click="handleCreate()">发布商品</el-button>
            <el-button type="primary" @click="viewPurchaseList()">购买记录</el-button>
            <el-input style="width:500px;margin-left: 10px;" v-model="searchText" placeholder="输入关键词搜索" clearable @keyup.enter="handleSearch" @clear="clearSearch">
                <template #prefix>
                	<el-icon class="el-input__icon"><search /></el-icon>
                </template>
				<template #append>
                    <el-button @click="handleSearch">搜索</el-button>
                </template>
			</el-input>
        </div>

		<!-- 数据表格 -->
		<el-table class="mt-1" :data="product" :row-key="(row) => row.ID" border table-layout="auto" stripe empty-text="暂无商品数据">
		    <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
			<el-table-column prop="Name" label="商品名称" min-width="260" show-overflow-tooltip></el-table-column>
            <el-table-column prop="HiddenContent" label="付费内容" min-width="200" show-overflow-tooltip></el-table-column>
			<el-table-column label="缩略图" prop="Photo" width="120" align="center">
				<template #default="{ row }">
					<el-image style="width: 80px; height: 60px; border-radius: 4px" :src="row.Photo" :preview-src-list="[row.Photo]" fit="cover" v-if="row.Photo">
						<template #error>
							<div class="image-error">
								<el-icon>
									<Picture />
								</el-icon>
							</div>
						</template>
					</el-image>
					<el-icon v-else size="40">
						<Picture />
					</el-icon>
				</template>
			</el-table-column>
			
		    <el-table-column prop="Points" label="所需积分" align="center" />
			<el-table-column prop="Stock" label="库存" align="center" />
			<el-table-column prop="IsAvailable" label="上架" align="center">
                <template #default="scope">
                    <el-tag :type="scope.row.IsAvailable ? 'success' : 'info'" effect="dark">
                        {{ scope.row.IsAvailable ? '是' : '否' }}
                    </el-tag>
                </template>
            </el-table-column>
			<el-table-column label="创建时间" width="180">
				<template #default="{ row }">{{ $validators.formatDate(row.CreatedAt) }}</template>
			</el-table-column>
            <el-table-column fixed="right" label="操作" :width="180">
                <template #default="scope">
                <el-button link type="success" @click="viewproduct(scope.row.ID)">查看</el-button>
                <el-button link type="primary" @click="handleEdit(scope.row)">修改</el-button>
                <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
		</el-table>

		<!-- 分页 -->
		<div class="pagination">
			<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
				:page-sizes="[10, 20, 50, 100]" :background="true" layout="total, sizes, prev, pager, next"
				:total="total" @size-change="handlePageChange" @current-change="handlePageChange" />
		</div>

	</div>
        `
    }